<?php
/**
 * User Actually data content 
 *
 */
class MA_Apis_User  
{
	private $_userId = false;
	private $_username;
	private $_mail;
	private $_applications = array();
	private $_token;
	private $_lastIp;
	private $_loginDate;
	private $_userLov = array();
	private $_cookie;
	private $_config;	
	private $_userModel;
	private $_UserProperties;
	const ACTIVE = 1;
	const TO_ACTIVE = 0;
	public function __construct()
	{
		$this->_config = Zend_Registry::get( 'config_ini' );
		$this->_userModel = new Users();
		$this->_UserProperties = new UserProperties();
	}
	/**
	 * Instanciar un usuario. 
	 */
	public function init()
	{
		if( isset( $_COOKIE['token'] )) {
			
			
			$statusUserLogin = new StatusUserLogin();
			$row = $statusUserLogin->find( $_COOKIE['token'] )->current();
			if( $row == null ) {
				return $this->_initializeUser();
			}
			$this->_token = $row->token;
			$this->_lastIp = $row->last_ip;
			$this->_loginDate = $row->login_date;
			
			/** Check if user autenticated */
			if( $row->user_id == 0 ) {
				$this->_userId = 0;
				/** Return User don't autenticated */
			} else {
				$this->_userId = ( int ) $row->user_id;
				$this->_fillUserData();
			}
		} else {
			$this->_initializeUser();
		}
		return true;
	}
	/**
	 * Fill data user, in this class
	 */
	private function _fillUserData()
	{
		
		$userData = $this->_userModel->find( $this->_userId )->current();
		$this->_username =  $userData->username;
		$this->_mail =  $userData->mail;		
	}

	/**
	 * Inicia el ingreso al sistema
	 * Esto significa crear la cookie con un token aleatorio, y guardar el registro
	 * en la base de datos, para ir completando los datos una vez registrado.
	 * 
	 */
	private function _initializeUser()
	{ 
		$this->_lastIp = $_SERVER['REMOTE_ADDR'];
		$this->_token =  md5( time() );
    	$this->_cookie = setcookie("token"
    		, $this->_token 
    		, time()+7200 
    		, "/" 
    		, $this->_config->site->cookie->domain );
	    /**
	     * Persistimos los datos en la base
	     */
    	$statusUserLogin = new StatusUserLogin();
    	$status = $statusUserLogin->createRow();
    	$status->user_id = 0;
    	$status->token = $this->_token;
    	$status->last_ip = $this->_lastIp;
	   	$status->save();
    }
	/**
	 * Autentica un usuario si los datos pasados son correctos 
	 * @param string $username
	 * @param string $password
	 * @param string $service
	 * @use this->findId()
	 * @return mixed
	 */
	public function login( $username, $password, $service = null )
	{
		$userAppModel = new UserApplications();
		$appModel = new Applications();
		$userId = $this->_userModel->findId( $username );
		if( $userId == 0 ){
			return false;
		}
		$status = new StatusUserLogin();
		$row = $status->find( $this->_token )->current();
		$row->user_id = $userId;
		$row->login_date = new Zend_Db_Expr( 'NOW()' );
		$row->save();
		if( $service != null ) {
			$app = $appModel->fetchRow( "code = '$service' "  );
			if( empty($app ) ) {
				return MA_Error_Application::getInstance()->get('APP_DONT_EXIST');
			}
			$row = $userAppModel->find( array($app->application_id, $userId) )->current();
			if( empty( $row )){
				/** If user don't take permision for this application, try create else return app error */
				return MA_Error_Application::getInstance()->get('APP_DONT_ACCESS'); 				
			} else {
				return true;
			}		
		}		
		return true;		
		/*
		$authAdapter = new Zend_Auth_Adapter_DbTable (
			Zend_Db_Table::getDefaultAdapter(),
		    'users','user_id','password', "MD5(?)");
		$authAdapter->setIdentity( $userId );
		$authAdapter->setCredential( $userData['password'] );
		$result = Zend_Auth::getInstance()->authenticate( $authAdapter );
		if ($result->isValid()) {
        	$this->username = $userData['username'];
            $this->userId = $userId;
            /**
             * Obtengo las aplicaciones donde el usuario tiene permiso
             * @var UserApplications
             */
            /*$appUserModel = new UserApplications();
			$this->_applications = 	$appUserModel->getApplicationsFromUserinArray( $this->_userId );
			return $this->_applicationDelegate( $userData['appId'] ); 
		} else {
			return false;
		}
		*/
	}
	public function getProfile()
	{
		$adapter = Zend_Registry::get( 'dbAdapter');
		$query = $adapter->select()
			->from( array( 'u' => 'users') , '')
			->join( array('up'=>'user_properties'), 'up.user_id = u.user_id ', 'up.*' )
			->where( 'u.user_id = ?', $this->_userId );
		$rows = $adapter->fetchAll( $query );
		$userData = array();
		$userData['user_id'] = $this->_userId;
		$userData['username'] = $this->_username;
		$userData['mail'] = $this->_mail;
		
		foreach( $rows as $row ) {
			$userData[ $row['name'] ] = $row['value'];
			
		}
		return $userData;
	}
	public function update( array $userData )
	{
				
	}
	/**
	 * Determina si el usuario tiene permiso para usar la aplicacion actual.
	 * @param integer $appId
	 * @return boolean
	 */
	public function applicationValidate( $applicationId ) 
	{
		if( in_array( $applicationId, $this->_applications ) ) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * Activa un usuario a partir del token
	 *
	 * @param string $token
	 */
	public function activate( $token )
	{
		$userToActivate = new UserToActivate();
		$row = $userToActivate->find( $token )->current();
		if( $row == null ) {
			return false;
		} else {
			$user = $this->_userModel->find( $row->user_id )->current();
			$user->status = self::ACTIVE;
			$user->save();
			$row->delete();
			return true;	
		}
		
	}
	/**
	 * Genera un registro temporal para activar un usuario para esto
	 * Genera un hash, y envia la url de confirmacion por mail.
	 *
	 * @param string $userId
	 */
	public function confirmAccount( $userId )
	{
		$token = md5( time() . $userId );
		$UserToActivate = new UserToActivate();
		$row = $UserToActivate->createRow();
		$row->user_id = $userId;
		$row->token = $token;
		$row->save();
		
		return $this->_sendMailToConfirmationAccount( $userId, $token );
	}
	private function _sendMailToConfirmationAccount( $userId, $token)
	{
		echo "Enviamos el mail con la siguiente url" . $userId;
		echo "<br/><br/><br/>http://manageraccount.dev/user/active/token/" . $token ."/";
		return true;
	} 
	/**
	 * Validador de datos del usuario
	 * @param array $userData
	 * @return boolean true|false
	 */
	private function _fieldValidate( $userData )
	{
		$userData['mail_confirm'] = $userData['mail'];
		$userData['password_confirm'] = $userData['password']; 
		$form = new MA_Forms_Register();
		if( ! $form->isValid( $userData ) ) {
			return MA_Error_User::getInstance()->get( 'DATA_ERROR' );
		}
		return true;
	}
	private function _saveProperties( $userData )
	{
		$this->_UserProperties->createRow();
		$this->_UserProperties->user_id = $userData['user_id'];
		$this->_UserProperties->key = 'first_name';
		$this->_UserProperties->value = $userData['first_name'];
		$this->_UserProperties->save();

		$this->_UserProperties->createRow();
		$this->_UserProperties->user_id = $userData['user_id'];		
		$this->_UserProperties->key = 'last_name';
		$this->_UserProperties->value = $userData['last_name'];
		$this->_UserProperties->save();		
	}
	private function _exists( $username, $mail ) 
	{
		$userModel = new Users();
		$row = $userModel->fetchAll( $userModel->select()
			->where( 'username = ?', $username)
			->orWhere( 'mail = ?', $mail ) );
		return count( $row );
	}
	/**
	 * Armar un Zend Form. Validar todos los datos chequear que todos los datos no existan. 
	 * @param array userData
	 */
	public function register( $userData )
	{
		if( $this->_exists( $userData['username'], $userData['mail'] )) {
			return MA_Error_User::getInstance()->get('EXISTS');
		}
		/**
		 * Validacion de datos
		 */
		$validation = $this->_fieldValidate( $userData );
		if( $validation ){
			return $this->_saveUser ( $userData );
		//	$this->_saveProperties( $userData );
		} else {
			return $validation;
		}
	}
	/**
	 * Persiste el usuario en la base de datos
	 *
	 * @param array $userData
	 * @return int
	 */
	private function _saveUser ( $userData ) 
	{
		$newUser = $this->_userModel->createRow();
		$newUser->username = $userData['username'];
		$newUser->mail = $userData['mail'];
		$newUser->password = $this->_userModel->tokenizer( $userData['password'] ) ;
		$newUser->status = self::TO_ACTIVE;
		return ( int ) $newUser->save();
	}
	public function resetPassword()
	{
		
	}
	public function changeUsername()
	{
	}
	public function changeMail()
	{
	}
	public function changePassword()
	{
	}
	/**
	 * Get Info from User
	 * @param int $userId
	 * @return mixed array|string
	 */ 
	public function getInfo( $userId )
	{
		$query = $this->_userModel->select()
			->where( 'user_id = ?', $userId );
		$userData = $this->_userModel->fetchAll( $query );
		if( $userData == null ) {
			return MA_Error_User::getInstance()->get('NOT_EXISTS');
		} else {
			return $userData->toArray();
		}
	}

	public function __get( $key )
	{
		$key = '_' . $key;
		return $this->$key;
	}
	public function __set( $key, $value )
	{
		$key = '_' . $key;
		$this->$key = $value;
	}
	private function _applicationDelegate( $appId ) 
	{
		if( $appId ) {
			$appModel = new Applications();
			$app = $appModel->find( $appId )->current();
			if( $app == null ) {
				return '/user/profile/';
			} else {
				if( $this->_user->applicationValidate( $appId ) === true ) {
					return 'http://' .$app->domain ;
				} else {
					if( $app->dinamic_register == 1 ) {
						$this->_user->addUserToApplication( $appId  );
						return 'http://' .$app->domain ;	 
					} else {
						return '/user/profile/' ;
					}			                				
				}
			}
		} else {
			return '/user/profile/';
		}
	}
}
